package cn.demo.common.utils;

import cn.demo.common.constant.CommonConstants;
import cn.demo.common.constant.HttpStatus;
import cn.demo.common.core.domain.model.LoginUser;
import cn.demo.common.exception.ServiceException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.PatternMatchUtils;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import static cn.demo.common.constant.CommonConstants.ADMIN_ID;

/**
 * 安全服务工具类
 *
 * @author ruoyi
 */
@Slf4j
public class SecurityUtils {

    /**
     * 用户ID
     **/
    public static String getUserId() {
        try {
            LoginUser loginUser = getLoginUser();
            if (null != loginUser){
                return loginUser.getUserId();
            }else {
                return null;
            }
        } catch (Exception e) {
            throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取部门ID
     **/
    public static String getDeptId() {
        try {
            LoginUser loginUser = getLoginUser();
            if (null != loginUser){
                return loginUser.getDeptId();
            }else {
                return null;
            }
        } catch (Exception e) {
            throw new ServiceException("获取部门ID异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取部门ID及子部门id
     **/
    public static Set<String> getDeptIds() {
        try {
            LoginUser loginUser = getLoginUser();
            if (null != loginUser){
                return loginUser.getDeptIds();
            }else {
                return null;
            }
        } catch (Exception e) {
            throw new ServiceException("获取部门ID异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户账户
     **/
    public static String getUsername() {
        try {
            LoginUser loginUser = getLoginUser();
            if (null != loginUser){
                return loginUser.getUsername();
            }else {
                return null;
            }
        } catch (Exception e) {
            throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser() {
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            // log.warn("获取登录用户名警告 => 用户未登录");
            return null;
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 是否为管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(String userId) {
        return ADMIN_ID.equals(userId);
    }
    public static boolean isAdmin(LoginUser loginUser) {
        return null == loginUser || loginUser.getUserId().equals(ADMIN_ID) || isAdmin(loginUser.getRoleKeys());
    }
    public static boolean isAdmin(Set<String> roles) {
        return hasRole(roles,CommonConstants.ADMIN_ROLE);
    }
    public static boolean isAdmin() {
        return isAdmin(getLoginUser());
    }
    /**
     * 验证用户是否具备某权限
     *
     * @param permission 权限字符串
     * @return 用户是否具备某权限
     */
    public static boolean hasPermi(String permission) {
        return hasPermi(getLoginUser().getPermissions(), permission);
    }

    /**
     * 判断是否包含权限
     *
     * @param authorities 权限列表
     * @param permission  权限字符串
     * @return 用户是否具备某权限
     */
    public static boolean hasPermi(Collection<String> authorities, String permission) {
        return authorities.stream().filter(StringUtils::hasText)
                .anyMatch(x -> CommonConstants.ALL_PERMISSION.equals(x) || PatternMatchUtils.simpleMatch(x, permission));
    }

    /**
     * 验证用户是否拥有某个角色
     *
     * @param role 角色标识
     * @return 用户是否具备某角色
     */
    public static boolean hasRole(String role) {

        return hasRole(getRoleList(), role);
    }

    /**
     * 判断是否包含角色
     *
     * @param roles 角色列表
     * @param role  角色
     * @return 用户是否具备某角色权限
     */
    public static boolean hasRole(Collection<String> roles, String role) {
        if (CollectionUtils.isEmpty(roles)) {
            return false;
        }
        return roles.stream().filter(StringUtils::hasText)
                .anyMatch(x -> CommonConstants.ADMIN_ROLE.equals(x) || PatternMatchUtils.simpleMatch(x, role));
    }

    /**
     * 获取当前账号的角色列表
     *
     * @return 角色列表
     */
    public static Set<String> getRoleList() {
        try {
            LoginUser loginUser = getLoginUser();
            return loginUser.getRoleKeys();
        } catch (Exception e) {
            return new HashSet<>();
        }
    }

    /**
     * 获取请求token
     */
    public static String getToken() {
        return getToken(ServletUtils.getRequest());
    }

    /**
     * 根据request获取请求token
     */
    public static String getToken(HttpServletRequest request) {
        if (null == request){
            return null;
        }
        // 从header获取token标识
        String token = request.getHeader(CommonConstants.AUTHENTICATION);
        return replaceTokenPrefix(token);
    }

    /**
     * 裁剪token前缀
     */
    public static String replaceTokenPrefix(String token) {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(CommonConstants.TOKEN_PREFIX)) {
            token = token.replaceFirst(CommonConstants.TOKEN_PREFIX, "");
        }
        return token;
    }

}
